<template>
  <div class="account-module">
    <div class="register" :style="{ background: 'url(' + bgImg + ') center  top', backgroundSize: '100% auto', 'min-height':'1050px' }">
      <div class="header">
        <div class="left">
          <img class="min"  src="@/assets/logo_min.png" />
          <div class="title">全国青少年无人机大赛 | 用户管理中心</div>
        </div>
        <img class="logo" src="@/assets/r-logo.png" />
      </div>
      <div class="c" style="width: 1136px;">
        <el-form
          ref="ruleFormRef"
          :model="ruleForm"
          :rules="rules"
          label-width="120px"
          class="ruleForm"
          :size="formSize"
          status-icon
        >
        <div class="regisetr-title">用户注册</div>


          <el-form-item label="一寸证件照" prop="header">
            <el-upload :disabled="editFlag.header"
            class="avatar-uploader"
            :action="baseUrl+'/front/upload'"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
            >
                <div class="image" style="width: 100px; height: 140px;">
                    <img v-if="imageUrl" :src="imageUrl" class="img" />
                    <div v-else class="upload">
                        <img src="@/assets/common/upload.png">
                        <div class="text">上传一寸照片</div>
                    </div>
                       
                </div>
                <div class="hint">支持JPG/JPEG/PNG格式，不超过1MB，本信息将导入证件制作系统，<br/> 请上传本人一寸近照！
                    </div>    
            </el-upload>
          </el-form-item>

        </el-form>
      </div>
    </div>
  </div>

</template>
<script lang="ts" setup>
import app from "@/constants/app";
import { reactive, ref } from "vue";
import type { FormInstance, FormRules } from "element-plus";

import type { UploadProps } from 'element-plus'
import baseService from "@/service/baseService";
import {setCache} from "@/utils/cache";
import {ElMessage} from "element-plus";
import { useRouter } from "vue-router";
let router = useRouter();

const bgImg = require('../../assets/bg.png')
const imageUrl = ref('')
const imageUrl2 = ref('')
const formSize = ref("default");
const ruleFormRef = ref<FormInstance>();
const ruleForm = reactive({
  id : "",
  roleId: "",
  roleIds: [] as any,
  realName: "",
  sex: "",
  idType: "",
  idCard: "",
  company: "",
  code: "",
  phone: "",
  password: "",
  email: "",
  header: "",
  empower: ""
});
const editFlag = reactive({
  realName: false,
  sex: false,
  idType: false,
  idCard: false,
  company: false,
  phone: false,
  password: false,
  email: false,
  header: false,
});
const baseUrl = app.api;
const isLock = ref(true);
// 数组
const roleSelected = ref([]);

const roleList = reactive([
  {
    label: "代表队负责人",
    value: '0',
    checked: false,
    disabled: false
  },
  {
    label: "领队",
    value: '1',
    checked: false,
    disabled: false
  },
  {
    label: "指导老师",
    value: '2',
    checked: false,
    disabled: false
  },
  {
    label: "选手",
    value: '3',
    checked: false,
    disabled: false
  },
]);

const dialogShow = ref(false);

const rules = reactive<FormRules>({
  roleIds: [
    {
      required: true,
      message: "请选择用户类型",
      trigger: "change",
    },
  ],
  realName: [{ required: true, message: "请输入姓名", trigger: "blur" }],
  sex: [
    {
      required: true,
      message: "请选择性别",
      trigger: "change",
    },
  ],
  idType: [
    {
      required: true,
      message: "请选择证件",
      trigger: "change",
    },
  ],
  idCard: [{ required: true, message: "请输入证件号码", trigger: "blur" }],
  company: [{ required: true, message: "请输入参赛单位", trigger: "blur" }],
  phone: [{ required: true, message: "请输入手机号", trigger: "blur" }],
  header: [{ required: true, message: "请上传一寸证件照", trigger: "blur" }],
  password: [{ required: true, message: "请输入验证码", trigger: "blur" }],
});

const btns = reactive({
  sendmsg: "发送验证码",
  disabled: false
});


/**
 * 短信验证码倒计时功能
 */
let timer: any = null;
const countDown = () => {
  let count = 60;
  btns.disabled = true;
  btns.sendmsg = count + "s后重新发送";
  timer = setInterval(() => {
    count--;
    btns.sendmsg = count + "s后重新发送";
    if (count <= 0) {
      clearInterval(timer);
      btns.sendmsg = "发送验证码";
      btns.disabled = false;
    }
  }, 1000);
};


/**
 * 查询用户信息
 * @param formEl
 */
const registerValidate = async (formEl: FormInstance | undefined) => {
  //姓名不能为空
  if (ruleForm.realName === "") {
    ElMessage.error("姓名不能为空！");
    return;
  }
  //校验手机号不能为空
  if (ruleForm.phone === "") {
    ElMessage.error("手机号不能为空！");
    return;
  }
  baseService
      .post("/front/spuser/registerValidate", {
        realName: ruleForm.realName,
        phone: ruleForm.code + ruleForm.phone,
        password: ruleForm.password
      })
      .then((res) => {
            if (res.code === 0) {
              ruleForm.id = res.data.id;
              ruleForm.idType = res.data.idType;
              ruleForm.idCard = res.data.idCard;
              ruleForm.sex  = res.data.sex+'';
              ruleForm.email = res.data.email;
              ruleForm.company = res.data.company;
              ruleForm.header = res.data.header;
              ruleForm.roleIds = res.data.roleId ? res.data.roleId.split(",") : [];
              imageUrl.value = res.data.header;
              //禁用姓名和手机号
              editFlag.realName = true;
              editFlag.phone = true;
              editFlag.sex = true;
              editFlag.idType = true;
              editFlag.idCard = true;
              editFlag.company = true;
              editFlag.email = true;
              editFlag.header = true;
              let roles = res.data.roleId ? res.data.roleId.split(",") : [];
              //遍历角色
              roleList.forEach((item) => {
                if (roles.includes(item.value)) {
                  item.disabled = true;
                }
              });
              changeRole(roles);

            } else {
              ElMessage.error(res.msg);
            }
          }
      );
};

/**
 * 提交表单-注册
 * @param formEl
 */
const submitForm = async (formEl: FormInstance | undefined) => {
  // 设置按钮不可点击（disable: false）
  isLock.value = true
  if (!formEl) {
    return;
  }
  await formEl.validate((valid, fields) => {
    if (valid) {
      ruleForm.roleId = ruleForm.roleIds.join(",");
      // 拷贝对象
      let registerForm = JSON.parse(JSON.stringify(ruleForm));
      registerForm.phone = ruleForm.code + ruleForm.phone;
      baseService
          .post("/front/spuser/register", registerForm)
          .then((res) => {
                if (res.code === 0) {
                  //提示注册成功
                  ElMessage.success("注册成功");
                  //3s后执行
                  setTimeout(() => {
                    // 统一跳转到登录页面
                    router.push("/");
                  }, 2000);
                } else {
                  ElMessage.error(res.msg);
                }
              }
          );

    } else {
      console.log("error submit!", fields);
    }

  });
};

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
  router.push("/");
};


const handleAvatarSuccess: UploadProps['onSuccess'] = (
  response,
  uploadFile
) => {
  console.log('==========', response.data.src)
  ruleForm.header = response.data.src;
  imageUrl.value = URL.createObjectURL(uploadFile.raw!)
}

const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (!(rawFile.type == 'image/jpeg'||rawFile.type == 'image/png'||rawFile.type == 'image/jpg')) {
    ElMessage.error('仅支持JPG/JPEG/PNG格式!')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('一寸证件照不能超过2MB!')
    return false
  }
  return true
}


const handleAvatarSuccess2: UploadProps['onSuccess'] = (
    response,
    uploadFile
) => {
  ruleForm.empower = response.data.src;
  imageUrl.value = URL.createObjectURL(uploadFile.raw!)
}

const beforeAvatarUpload2: UploadProps['beforeUpload'] = (rawFile) => {
  //console.log('-------------', rawFile.type)
  if (!(rawFile.type == 'image/jpeg'||rawFile.type == 'image/png'||rawFile.type == 'image/jpg')) {
    ElMessage.error('仅支持JPG/JPEG/PNG格式!')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('一寸证件照不能超过2MB!')
    return false
  }
  return true
}


// 校验手机号格式
const checkPhone = () => {
  //校验手机号不能为空
  if (ruleForm.phone === "") {
    ElMessage.error("手机号格式不正确！");
    return false;
  }
  // 判断国际区号
  if (ruleForm.code === '') {
    if(ruleForm.phone.length != 11){
      ElMessage.error("手机号格式不正确！");
      return false;
    }
  } else if(ruleForm.code === '852') {
    if(!(ruleForm.phone.length == 8 || ruleForm.phone.length == 9)){
      ElMessage.error("手机号格式不正确！");
      return false;
    }
  } else if(ruleForm.code === '853') {
    if(ruleForm.phone.length != 8){
      ElMessage.error("手机号格式不正确！");
      return false;
    }
  }
  return true;
};


/**
 * 发送验证码
 */
const sendCode=()=>{
  //校验ruleForm.name不能为空
  if (ruleForm.phone === "") {
    ElMessage.error("手机号不能为空！");
    return;
  }
  // 校验手机号格式
  if(!checkPhone()){
    return;
  }
  if(btns.disabled) {
    return;
  }

  btns.sendmsg = "验证码已发送";
  baseService
      .post("/front/spuser/getCheckCode",{phone: ruleForm.code+ruleForm.phone, code:ruleForm.code}  )
      .then((res) =>
          {
            if (res.code === 0) {
              ElMessage.success('验证码发送成功');
              countDown();
            }
          }
      );
}

/**
 * 用户类型变更事件
 * 1、选手身份是独立的，选了选手其他3项不能选择
 * 2、代表队和领队是不兼容的
 * @param value
 */
const changeRole = (value: any) => {
  //ElMessage.success('当前选择: ' + value);
  //代表队和领队是不兼容的
  if (value.includes('0')){
    roleList[1].disabled = true;
    roleList[3].disabled = true;
  }
  //代表队和领队是不兼容的
  if (value.includes('1')){
    roleList[0].disabled = true;
    roleList[3].disabled = true;
  }
  // 只有指导老师时，选手禁用
  if (value.length==1 && value.includes('2')){
    roleList[0].disabled = false;
    roleList[1].disabled = false;
    roleList[3].disabled = true;
  }
  // value中包含选手3 则给出提示"选手身份是独立的"
  if (value.includes('3')) {
    //ElMessage.warning('选手身份是独立的');
    //roleList 把除了3以外的其他选项全部禁用并取消选中
    roleList.forEach((item)=>{
      if(item.value=='0' || item.value=='1' || item.value =='2'){
        item.disabled=true;
      }
    })
    ruleForm.roleIds = ['3'];
  }
  if(value.length==0){
    roleList.forEach((item)=>{
      item.disabled=false;
    })
  }

};

</script>
<style lang="scss" scoped>
@import "./account.scss";
</style>
<style lang="scss">
.ruleForm {
  .el-form-item--default .el-form-item__label {
    font-weight: $font-weight-bold;
  }
}
</style>
